# -*- coding: utf-8 -*- 
"""
Created by hcx on 17-7-19 下午2:38.
@author: 胡超翔
"""
from __future__ import absolute_import
from __future__ import unicode_literals

import logging

from django.contrib import messages
# from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.urlresolvers import reverse_lazy
from django.db.models import Q
from django.http import HttpResponse
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
# from django.urls import reverse_lazy
# from django.views import View
from django.views.generic import DetailView
from django.views.generic import FormView
from django.views.generic import View

from autodeploy.apps.common.autocomplete import AutoCompleteView
from autodeploy.apps.common.search import SearchView
from autodeploy.apps.playbooks.models import PlayBooks
from autodeploy.apps.server.forms import ServerForm, ServerManageForm
from autodeploy.apps.server.models import Server, ServerManage

logger = logging.getLogger(__name__)


class ListServerManageView(LoginRequiredMixin, SearchView):
    """项目列表"""
    template_name = 'server/manage_list.html'
    model = ServerManage
    context_object_name = 'manage_list'
    name_list = ['name']

    def get_context_data(self, **kwargs):
        context = super(ListServerManageView, self).get_context_data(**kwargs)
        # context[self.context_object_name]=
        return context


class EditorServerManageView(LoginRequiredMixin, FormView):
    """项目编辑"""
    template_name = 'server/manage_editor.html'
    form_class = ServerManageForm
    success_url = reverse_lazy('server:manage_list')
    
    def get_form_kwargs(self):
        kwargs = super(EditorServerManageView, self).get_form_kwargs()
        smid = self.kwargs.get('smid', None)  # 链接里的参数
        
        if smid:
            self.server_manage = get_object_or_404(ServerManage, pk=int(smid))
            kwargs['instance'] = self.server_manage
        else:
            self.server_manage = ServerManage()
        return kwargs
    
    # def get_queryset(self):
    #
    #     return super(ProductAddEditView, self).get_queryset()
    
    def get_context_data(self, **kwargs):
        context = super(EditorServerManageView, self).get_context_data(**kwargs)
        # 这里可以自己加参数
        context['smid'] = self.server_manage.id
        return context
    
    def form_valid(self, form):
        self.server_manage = form.save()
        messages.info(self.request, u'编辑成功')
        self.success_url = reverse_lazy('server:manage_list')
        return super(EditorServerManageView, self).form_valid(form)


class DetailServerManageView(LoginRequiredMixin, DetailView):
    """该项目下的节点"""
    template_name = 'server/manage_detail.html'
    model = ServerManage
    context_object_name = 'server_list'
    name_list = ['ip']

    def get_context_data(self, **kwargs):
        context = super(DetailServerManageView, self).get_context_data(**kwargs)
        # context[self.context_object_name] = self.get_object().server_set.all()
        context[self.context_object_name] = self.get_server_list()
        return context

    def get_server_list(self):
        smid = self.kwargs.get('pk', '')
        if smid:
            server_list = self.get_object().server_set.filter(self.get_filter_tuple())
        else:
            server_list = []
            logger.info(u'未传出项目编号，无法搜索')
        return server_list

    def get_filter_tuple(self):
        """不需继承"""
        search_content = self.request.GET.get('searchaction', '')
        filter_info = Q()
        for name in self.name_list:
            kwargs = {
                '{}__{}'.format(name, 'icontains'): search_content
            }
            filter_info = filter_info | Q(**kwargs)
        return filter_info


class DeleteServerManageView(LoginRequiredMixin, View):
    """删除该服务器"""

    def get(self, request, *args, **kwargs):
        result = 0  # 0是删除失败
        try:
            smid = self.kwargs.get('smid', None)
            server_manage = ServerManage.objects.get(pk=smid)
            result = server_manage.update_delete()
            logger.info(u'%s删除服务器成功%s' % (request.user, smid))
        except Exception as e:
            logger.error(u'删除服务器出错,错误信息:%s' % e)
        
        return HttpResponse(result)


class ListServerView(LoginRequiredMixin, SearchView):
    """节点列表"""
    template_name = 'server/list.html'
    model = Server
    context_object_name = 'server_list'
    name_list = ['server_manage__name', 'ip']

    def get_context_data(self, **kwargs):
        context = super(ListServerView, self).get_context_data(**kwargs)
        # context[self.context_object_name]=
        return context


class EditorServerView(LoginRequiredMixin, FormView):
    """节点编辑"""
    template_name = "server/editor.html"
    form_class = ServerForm
    success_url = reverse_lazy('server:list')
    
    def get_form_kwargs(self):
        kwargs = super(EditorServerView, self).get_form_kwargs()
        sid = self.kwargs.get('sid', None)  # 链接里的参数
        
        if sid:
            self.server = get_object_or_404(Server, pk=int(sid))
            kwargs['instance'] = self.server
        else:
            self.server = Server()
        return kwargs
    
    # def get_queryset(self):
    #
    #     return super(ProductAddEditView, self).get_queryset()
    
    def get_context_data(self, **kwargs):
        context = super(EditorServerView, self).get_context_data(**kwargs)
        # 这里可以自己加参数
        context['sid'] = self.server.id
        context['server_manage'] = self.server.server_manage
        return context
    
    def form_valid(self, form):
        self.server = form.save()
        messages.info(self.request, u'编辑成功')
        self.success_url = reverse_lazy('server:list')
        return super(EditorServerView, self).form_valid(form)


class AutoCompleteManageListView(LoginRequiredMixin, AutoCompleteView):
    """创建节点时搜索匹配项目名"""
    model = ServerManage
    name='name'

class DetailServerView(LoginRequiredMixin, DetailView):
    """服务器详情"""
    template_name = 'server/detail.html'
    model = Server
    
    def get_context_data(self, **kwargs):
        context = super(DetailServerView, self).get_context_data(**kwargs)
        context['play_books'] = self.get_object().playbooks.all()
        # context['operation_list'] = self.get_object().operationlog_set.all()
        return context


class DeleteServerView(LoginRequiredMixin, View):
    """删除服务器"""
    
    def get(self, request, *args, **kwargs):
        result = 0  # 0是删除失败
        try:
            sid = self.kwargs.get('sid', None)
            server = Server.objects.get(pk=sid)
            result = server.update_delete()
            logger.info(u'%s删除节点成功%s' % (request.user, sid))
        except Exception as e:
            logger.error(u'删除节点出错,错误信息:%s' % e)
        
        return HttpResponse(result)


class DeletePlayBooksRelationView(LoginRequiredMixin, View):
    """将剧本和服务器取关"""
    
    def post(self, request, *args, **kwargs):
        result = {'code': 0, 'msg': ''}
        server = self.get_server()
        play_book = self.get_play_book()
        if server and play_book:
            server.playbooks.remove(play_book)
            # server.save()
            logger.info('删除成功')
            result['code'] = 1
            result['msg'] = '删除成功'
        else:
            logger.error("删除失败，服务器或剧本不存在")
            result['msg'] = '删除失败，服务器或剧本不存在'
        return JsonResponse(result)
    
    def get_server(self):
        sid = self.request.POST.get('sid', '')
        try:
            server = Server.objects.get(pk=sid)
        except Exception as e:
            logger.error('不存在该服务器,错误:%s' % e)
            server = None
        return server
    
    def get_play_book(self):
        pbid = self.request.GET.get('pbid', '')
        try:
            play_book = PlayBooks.objects.get(pk=pbid)
        except Exception as e:
            logger.error('不存在该剧本,错误:%s' % e)
            play_book = None
        return play_book
